#!/bin/bash -e

TOP_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." &> /dev/null && pwd )"
VALUES_FILE=$TOP_DIR/deploy/charts/harvester/values.yaml

: ${INSTALLER_BRANCH:="master"}

if [ -z ${WORK_DIR+x} ]; then
  WORK_DIR=$(mktemp -d)
  trap "rm -rf $WORK_DIR" EXIT
fi

META_FILE=$WORK_DIR/deps.txt


get_installer_tag() {
  local line=$(grep -e "^HARVESTER_INSTALLER_VERSION=" $TOP_DIR/scripts/build-iso)
  echo ${line#"HARVESTER_INSTALLER_VERSION="}
}


build_meta() {
  # metadata format 
  # <git_URL> <branch_name> <version>
  # version:
  # (1) Just a version number with quote ("")
  # (2) A YAML key in values.yaml file
  cat > $META_FILE <<EOF
https://github.com/harvester/harvester-installer $INSTALLER_BRANCH "$(get_installer_tag)"
https://github.com/harvester/network-controller-harvester master .harvester-network-controller.image.tag
https://github.com/harvester/node-manager master .harvester-node-manager.image.tag
https://github.com/harvester/node-disk-manager master .harvester-node-disk-manager.image.tag
https://github.com/harvester/load-balancer-harvester master .harvester-load-balancer.image.tag
https://github.com/kube-vip/kube-vip main .kube-vip.image.tag
https://github.com/rancher/support-bundle-kit master .support-bundle-kit.image.tag
EOF
}

echo_warn() {
  printf "\033[1;31m[WARN]\033[0m $1\n"
}

echo_error() {
  printf "\033[0;31m[ERROR]\033[0m $1\n"
}

build_meta

fail_count=0

while read -r git_url branch image_path; do

  cd $WORK_DIR
  TAG=$(yq -e e $image_path $VALUES_FILE)
  echo ">> $git_url"
  echo ">> branch: $branch"
  echo ">> configured version: $TAG"

  project_dir=$(basename $git_url)
  if [ ! -d $project_dir ]; then
    echo "Clone $git_url..."
    git clone $git_url --quiet
    cd $project_dir
  else
    cd $project_dir && git pull --quiet
  fi

  if ! git diff $TAG origin/$branch --quiet; then
    echo_warn "Detect new commit(s) after tag ${TAG}! Latest 3 commits:"
    git --no-pager log $TAG..origin/$branch --oneline | head -n 3
    fail_count=$((fail_count+1))
  fi
  echo ""

done < $META_FILE


if [ $fail_count -gt 0 ]; then
  echo_error "There are $fail_count failing check(s)."
  exit 1
fi
